package com.ctgu.myshop.api.gateway.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.rpc.RpcContext;
import com.ctgu.myshop.service.content.api.ContentConsumerService;
import com.ctgu.myshop.service.user.api.UserConsumerService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "router")
public class RouterController {

    @Value(value = "${services.ports.user}")
    private String userPort;

    @Value(value = "${services.ports.content}")
    private String contentPort;

    @Reference(version = "${services.versions.user.v1}")
    private UserConsumerService userConsumerService;

    @Reference(version = "${services.versions.content.v1}")
    private ContentConsumerService contentConsumerService;

    @GetMapping(value = "user")
    public String user(String path){
        userConsumerService.info();
        return getRequest(userPort, path);
    }

    @GetMapping(value = "content")
    public String content(String path){
        contentConsumerService.info();
        return getRequest(contentPort, path);
    }

    public String getRequest(String port, String path){
        boolean isConsumerSide = RpcContext.getContext().isConsumerSide();
        if(isConsumerSide){
            String serverIP = RpcContext.getContext().getRemoteHost();
            return String.format("redirect:http://%s:%s%s", serverIP, port, path);
        }
        return null;
    }

}
